package com.zwps.biz.controller.http;


import com.zwps.biz.controller.config.SSLHelper;
import com.zwps.biz.dal.db.object.WeatherRadarDO;
import com.zwps.biz.domain.service.PubPointAllService;
import com.zwps.biz.domain.service.WeatherRadarService;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Tag(name = "气象台api")
@RestController
@RequestMapping("/brief/nmc")
public class NmcController {
    @Autowired
    WeatherRadarService weatherRadarService;

    @Autowired
    private RestTemplateBuilder restTemplate;

    @Autowired
    private PubPointAllService pubPointAllService;

    @GetMapping("/saveNmcDate")

    @Scheduled(cron = "0 0 * * * ?")
    public void saveWeatherRadar() {
        fetchAndSaveRadarData("https://www.nmc.cn/publish/tianqishikuang/leidatu/danzhanleida/hubei/huanggang/index.html",1);
        fetchAndSaveRadarData("https://www.nmc.cn/publish/satellite/fy4b-visible.htm",2);
        fetchAndSaveRadarData("https://www.nmc.cn/publish/observations/hourly-precipitation.html",3);
    }

    public void fetchAndSaveRadarData(String url,int type){
        List<WeatherRadarDO> list = new ArrayList<>();
        try {

            Connection connection = Jsoup.connect(url)
                    .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
                    .timeout(10000);

            // 禁用SSL验证
            connection.sslSocketFactory(SSLHelper.getInsecureSSLContext().getSocketFactory());
            Document doc = connection.get();
            ;
            // 2. 提取并处理雷达数据
            Elements radarItems = doc.select("div.col-xs-12.time");
            String currentYear = String.valueOf(LocalDateTime.now().getYear());

            // 3. 先查询已存在的时间点
            Set<LocalDateTime> existingTimes = weatherRadarService.getExistingTimes(type);

            for (Element item : radarItems) {
                String imgUrl = item.attr("data-img");
                String timeStr = item.attr("data-time");
                String fullTimeStr = currentYear + "/" + timeStr;

                try {
                    LocalDateTime radarTime = LocalDateTime.parse(fullTimeStr,
                            DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm"));

                    // 4. 检查时间是否已存在
                    if (!existingTimes.contains(radarTime)) {
                        WeatherRadarDO radarData = new WeatherRadarDO(currentYear, radarTime, imgUrl,type);
                        list.add(radarData);
                    }
                } catch (DateTimeParseException e) {

                }
            }

            // 5. 批量保存新数据
            if (!list.isEmpty()) {
                weatherRadarService.saveBatch(list);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/getNmcDate")
    public List<WeatherRadarDO> getWeatherRadar(@RequestParam(value = "startTime", required = false) String startTime,
                                                @RequestParam(value = "endTime", required = false) String endTime,
                                                @RequestParam(value = "type" ,required = false) Integer type) {
        return weatherRadarService.getWeatherRadar(startTime, endTime,type);
    }


}
